using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using SqlsugarService.Application.AI.LangChain;
using SqlsugarService.Application.AI.LangChain.Dtos;
using System.ComponentModel.DataAnnotations;

namespace SqlsugarService.API.Controllers
{
    /// <summary>
    /// LangChain智能对话控制器
    /// 
    /// 提供基于LangChain.NET的AI交互接口，包括：
    /// - 发送消息并获取回复
    /// - 快速发送消息（使用默认配置）
    /// - 清除会话历史
    /// - 健康检查
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    [Produces("application/json")]
    public class LangChainController : ControllerBase
    {
        private readonly ILangChainService _langChainService;
        private readonly ILogger<LangChainController> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="langChainService">LangChain服务</param>
        /// <param name="logger">日志记录器</param>
        public LangChainController(ILangChainService langChainService, ILogger<LangChainController> logger)
        {
            _langChainService = langChainService ?? throw new ArgumentNullException(nameof(langChainService));
            _logger = logger ?? throw new ArgumentNullException(nameof(logger));
        }

        /// <summary>
        /// 发送消息到LangChain并获取回复
        /// </summary>
        /// <param name="request">请求参数，包含消息内容、用户ID等</param>
        /// <returns>AI的回复内容</returns>
        /// <response code="200">请求成功，返回AI回复</response>
        /// <response code="400">请求参数无效</response>
        /// <response code="500">服务器内部错误</response>
        [HttpPost("send-message")]
        [ProducesResponseType(typeof(LangChainResponseDto), StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status400BadRequest)]
        [ProducesResponseType(StatusCodes.Status500InternalServerError)]
        public async Task<ActionResult<LangChainResponseDto>> SendMessageAsync([FromBody] LangChainRequestDto request)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return BadRequest(ModelState);
                }

                _logger.LogInformation($"收到LangChain消息请求，内容长度: {request.Content?.Length ?? 0}");

                var result = await _langChainService.SendMessageAsync(request);

                if (result.Success)
                {
                    _logger.LogInformation($"LangChain消息处理成功，会话ID: {result.SessionId}");
                    return Ok(result);
                }
                else
                {
                    _logger.LogWarning($"LangChain消息处理失败: {result.ErrorMessage}");
                    return StatusCode(StatusCodes.Status500InternalServerError, result);
                }
            }
            catch (ArgumentException ex)
            {
                _logger.LogError(ex, "请求参数无效");
                return BadRequest(new { error = ex.Message });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "处理LangChain消息时发生未预期的错误");
                return StatusCode(StatusCodes.Status500InternalServerError,
                    new { error = "服务暂时不可用，请稍后重试" });
            }
        }

        /// <summary>
        /// 快速发送消息（使用默认配置）
        /// </summary>
        /// <param name="content">要发送的消息内容，不能为空</param>
        /// <param name="userId">用户ID，可选</param>
        /// <returns>AI的回复内容</returns>
        /// <response code="200">请求成功，返回AI回复</response>
        /// <response code="400">消息内容为空</response>
        /// <response code="500">服务器内部错误</response>
        [HttpPost("quick-send")]
        [ProducesResponseType(typeof(LangChainResponseDto), StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status400BadRequest)]
        [ProducesResponseType(StatusCodes.Status500InternalServerError)]
        public async Task<ActionResult<LangChainResponseDto>> QuickSendAsync(
            [FromBody, Required] string content,
            [FromQuery] string? userId = null)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(content))
                {
                    return BadRequest(new { error = "消息内容不能为空" });
                }

                _logger.LogInformation($"收到LangChain快速发送请求，内容长度: {content.Length}");

                var result = await _langChainService.QuickSendAsync(content, userId);

                if (result.Success)
                {
                    _logger.LogInformation($"LangChain快速发送成功，会话ID: {result.SessionId}");
                    return Ok(result);
                }
                else
                {
                    _logger.LogWarning($"LangChain快速发送失败: {result.ErrorMessage}");
                    return StatusCode(StatusCodes.Status500InternalServerError, result);
                }
            }
            catch (ArgumentNullException ex)
            {
                _logger.LogError(ex, "消息内容为空");
                return BadRequest(new { error = "消息内容不能为空" });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "LangChain快速发送消息时发生未预期的错误");
                return StatusCode(StatusCodes.Status500InternalServerError,
                    new { error = "服务暂时不可用，请稍后重试" });
            }
        }

        /// <summary>
        /// 清除指定用户的会话历史
        /// </summary>
        /// <param name="userId">用户ID，必填</param>
        /// <param name="sessionId">会话ID，可选，如果为空则清除该用户的所有会话</param>
        /// <returns>操作结果</returns>
        /// <response code="200">操作成功</response>
        /// <response code="400">参数无效</response>
        /// <response code="500">服务器内部错误</response>
        [HttpDelete("clear-memory")]
        [ProducesResponseType(typeof(bool), StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status400BadRequest)]
        [ProducesResponseType(StatusCodes.Status500InternalServerError)]
        public async Task<ActionResult<bool>> ClearMemoryAsync(
            [FromQuery, Required] string userId,
            [FromQuery] string? sessionId = null)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(userId))
                {
                    return BadRequest(new { error = "用户ID不能为空" });
                }

                _logger.LogInformation($"收到清除会话历史请求，用户ID: {userId}, 会话ID: {sessionId ?? "全部"}");

                var result = await _langChainService.ClearMemoryAsync(userId, sessionId);

                if (result)
                {
                    _logger.LogInformation($"清除会话历史成功，用户ID: {userId}");
                    return Ok(true);
                }
                else
                {
                    _logger.LogWarning($"清除会话历史失败，用户ID: {userId}");
                    return StatusCode(StatusCodes.Status500InternalServerError, false);
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "清除会话历史时发生未预期的错误");
                return StatusCode(StatusCodes.Status500InternalServerError,
                    new { error = "服务暂时不可用，请稍后重试" });
            }
        }

        /// <summary>
        /// 检查LangChain服务健康状态
        /// </summary>
        /// <returns>true表示服务正常，false表示服务异常</returns>
        /// <response code="200">健康检查成功</response>
        /// <response code="503">服务不可用</response>
        [HttpGet("health-check")]
        [ProducesResponseType(typeof(bool), StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status503ServiceUnavailable)]
        public async Task<ActionResult<bool>> HealthCheckAsync()
        {
            try
            {
                _logger.LogInformation("收到LangChain健康检查请求");

                var isHealthy = await _langChainService.HealthCheckAsync();

                if (isHealthy)
                {
                    _logger.LogInformation("LangChain健康检查通过");
                    return Ok(true);
                }
                else
                {
                    _logger.LogWarning("LangChain健康检查失败");
                    return StatusCode(StatusCodes.Status503ServiceUnavailable, false);
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "LangChain健康检查时发生错误");
                return StatusCode(StatusCodes.Status503ServiceUnavailable, false);
            }
        }
    }
} 